-- Adicionando coluna SCHEDULED_TASK.TP
CREATE OR REPLACE FUNCTION func_addColumn() RETURNS void AS $$
DECLARE
    VCOUNT  INTEGER := 0;
BEGIN
  SELECT count(*) into VCOUNT FROM pg_attribute WHERE attrelid='<SCHEMA>.scheduled_task'::REGCLASS AND attname = 'tp';
      IF VCOUNT = 0 THEN
          ALTER TABLE <SCHEMA>.SCHEDULED_TASK ADD TP NUMERIC(10, 0);
      END IF;
      RETURN;
END;

$$ LANGUAGE plpgsql;
SELECT func_addColumn();
 DROP FUNCTION func_addColumn();

COMMENT ON COLUMN <SCHEMA>.SCHEDULED_TASK.TP IS 'INDICA O TIPO DE TAREFA AGENDADA. (0) SIMPLES.';

-- Incluindo CK_SCHTSK_JT_1 na Tabela SCHEDULED_TASK
CREATE OR REPLACE FUNCTION func_dropCheckConstraint() RETURNS void AS $$
DECLARE
    VCOUNT  INTEGER := 0;
BEGIN
  SELECT COUNT(*) INTO VCOUNT FROM pg_constraint WHERE conrelid='<SCHEMA>.scheduled_task'::REGCLASS AND conname= 'ck_schtsk_jt_1';

      IF VCOUNT = 1 THEN
          ALTER TABLE <SCHEMA>.SCHEDULED_TASK DROP CONSTRAINT CK_SCHTSK_JT_1;
      END IF;
      RETURN;
END;

$$ LANGUAGE plpgsql;
SELECT func_dropCheckConstraint();
 DROP FUNCTION func_dropCheckConstraint();

ALTER TABLE <SCHEMA>.SCHEDULED_TASK ADD CONSTRAINT CK_SCHTSK_JT_1 CHECK ((TP = ANY (ARRAY[(0)::NUMERIC])));

UPDATE <SCHEMA>.SCHEDULED_TASK SET TP = 0;
ALTER TABLE <SCHEMA>.SCHEDULED_TASK ALTER COLUMN TP SET NOT NULL;
